package com.zhangshuo.config;

import com.zhangshuo.common.shiro.RetryLimitCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Map;

import java.util.HashMap;

/**
 * Created by Administrator on 2017/6/2 0002.
 */
@Configuration
@EnableCaching
public class RedisConfig {


    /**
     * 自定义redisTemplate的参数
     * 自定义字符串的序列化方式
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    @Autowired
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate();
        //默认使用JDK的序列化工具，用String序列化工具在logout时会出现问题
        //redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 自定义的redis的cacheManager
     * 根据名字获取cache,实质上是加了一个前缀，同一个前缀默认为一个Cache
     * @param redisTemplate
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate){
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        redisCacheManager.setDefaultExpiration(600);
        redisCacheManager.setUsePrefix(true);
        Map<String,Long> expires = new HashMap<>();
        expires.put("halfHour",1800L);
        expires.put("hour",3600L);
        expires.put("oneDay",86400L);
        expires.put("authorizationCache",1800L);
        expires.put("authenticationCache",1800L);
        expires.put("activeSessionCache",1800L);
        redisCacheManager.setExpires(expires);
        //默认的失效时间 默认时间是永不失效
        redisCacheManager.setDefaultExpiration(1800L);
        return redisCacheManager;
    }


}
